import { Tabs, Button, Table, Space, Modal, Form, Input, message, Alert } from 'antd'
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons'

import styles from './index.module.scss'
import request from '../../utils/request'
import { useEffect, useState } from 'react'
import { IModal, IParams, IRoleItem } from './setting'
import TextArea from 'antd/lib/input/TextArea'
import { useSelector } from 'react-redux'
import { RootState } from '../../store'
const { TabPane } = Tabs
const { confirm } = Modal

const Employees = () => {
  const [form] = Form.useForm()
  const { userInfo } = useSelector((state: RootState) => state.login)

  const columns = [
    {
      title: '角色名',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description'
    },
    {
      title: '操作',
      key: 'action',
      render: (text: any, record: any) => (
        <Space size="middle">
          <Button style={{ backgroundColor: '#67C23A', color: '#fff' }}>分配角色</Button>
          <Button type="primary" onClick={() => onRowEdit(record)}>
            编辑
          </Button>
          <Button danger={true} onClick={() => onRowDelete(record)}>
            删除
          </Button>
        </Space>
      )
    }
  ]

  const [params, setParams] = useState({
    page: 1, // 当前页面
    pagesize: 5 // 页面显示的条数
  } as IParams)

  const [roleList, setRoleList] = useState<IRoleItem[]>([])
  const [total, setTotal] = useState<number>()

  // 获取权限列表数据
  const getRolesList = async (params: IParams) => {
    const res = await request.get('/api/sys/role', { params })
    const { rows, total } = res.data.data
    setTotal(total)

    setRoleList(rows)
  }

  useEffect(() => {
    getRolesList(params)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [params])

  // 控制弹框隐藏
  const handleOk = async () => {
    const values = (await form.validateFields()) as IRoleItem

    if (propGroupModal.type === 'add') {
      const { name, description } = values
      await request.post('/api/sys/role', { name, description })

      message.info('新建成功', 0.5, () => {
        setPropGroupModal({
          ...propGroupModal,
          isShow: false
        })
        getRolesList(params)
      })
    } else if (propGroupModal.type === 'edit') {
      const { name, description, id } = values
      const { permIds } = editRole

      await request.put(`/api/sys/role/${id}`, { id, name, description, permIds })

      message.info('修改成功', 0.5, () => {
        setPropGroupModal({
          ...propGroupModal,
          isShow: false
        })
        getRolesList(params)
      })
    }

    setPropGroupModal({ ...propGroupModal, isShow: false })
  }

  // 控制弹框展示
  const handleCancel = () => {
    setPropGroupModal({ ...propGroupModal, isShow: false })
  }

  // -------------------------------  新增  ---------------------------------
  // 新建对话框
  const [propGroupModal, setPropGroupModal] = useState<IModal>({
    title: '新建属性组',
    isShow: false,
    type: 'add'
  })

  // 展示新建对话框
  const showAddModal = () => {
    setPropGroupModal({
      title: '添加角色',
      isShow: true,
      type: 'add'
    })
  }

  // -------------------------------  编辑  ---------------------------------

  const [editRole, setEditRole] = useState({} as IRoleItem)

  // 列表项编辑
  const onRowEdit = async (record: IRoleItem) => {
    console.log(record.id)

    const res = await request.get(`/api/sys/role/${record.id}`)
    setEditRole(res.data)
    form.setFieldsValue({ ...record, ...res.data })

    setPropGroupModal({
      title: '编辑角色',
      isShow: true,
      type: 'edit'
    })
  }

  // -------------------------------  删除  ---------------------------------

  const onRowDelete = (record: IRoleItem) => {
    confirm({
      title: '删除角色',
      icon: <ExclamationCircleOutlined />,
      content: '你确定需要删除该角色吗 ？',
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      async onOk() {
        await request.delete(`/api/sys/role/${record.id}`)

        message.info('删除成功', 0.5, () => {
          getRolesList(params)
        })
      },
      onCancel() {
        message.info('您取消了删除', 0.5)
      }
    })
  }

  // -------------------------------  删除  ---------------------------------
  // 当前页 - 改变
  const onPageChange = (page: number, pageSize?: number) => {
    console.log('page change', page, pageSize)
    setParams({
      ...params,
      page,
      pagesize: pageSize!
    })
  }

  const rules = {
    name: [{ required: true, message: '请输入角色名称' }],
    description: [{ required: true, message: '请输入角色描述' }]
  }

  // ----------------------------- 获取公司信息 -------------------------------
  const [companyForm] = Form.useForm()

  useEffect(() => {
    async function getCompanyInfo() {
      const res = await request.get(`/api/company/${userInfo.companyId}`)
      // setCompanyInfo(res.data.data)
      companyForm.setFieldsValue(res.data.data)
    }

    getCompanyInfo()
  }, [userInfo, companyForm])

  return (
    <div className={styles.root}>
      <Tabs defaultActiveKey="1">
        <TabPane tab="角色管理" key="1">
          <Button
            type="primary"
            icon={<PlusOutlined />}
            style={{ marginBottom: '10px' }}
            onClick={showAddModal}
          >
            新增角色
          </Button>

          <Table
            pagination={{
              position: ['bottomCenter'],
              total: total,
              pageSize: params.pagesize,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`,
              onChange: onPageChange
            }}
            rowKey={(record) => record.id}
            dataSource={roleList}
            columns={columns}
            bordered
          />
        </TabPane>
        <TabPane tab="公司信息" key="2">
          <Alert
            message="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
            type="info"
            showIcon
            style={{ marginBottom: '20px' }}
          />
          <Form
            form={companyForm}
            labelAlign="right"
            name="basic"
            labelCol={{ span: 2 }}
            wrapperCol={{ span: 8 }}
          >
            <Form.Item label="公司名称" name="name">
              <Input disabled />
            </Form.Item>

            <Form.Item label="公司地址" name="companyAddress">
              <Input disabled />
            </Form.Item>

            <Form.Item label="邮箱" name="mailbox">
              <Input disabled />
            </Form.Item>

            <Form.Item label="备注" name="remarks">
              <TextArea disabled rows={4} />
            </Form.Item>
          </Form>
        </TabPane>
      </Tabs>

      <Modal
        title={propGroupModal.title}
        visible={propGroupModal.isShow}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
        destroyOnClose
      >
        <Form
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 16 }}
          name="control-hooks"
          preserve={false}
          form={form}
        >
          {/* 编辑时，存储当前项id */}
          <Form.Item name="id" hidden>
            <Input type="hidden" />
          </Form.Item>

          <Form.Item label="角色名称" labelAlign="left" name="name" rules={rules.name}>
            <Input />
          </Form.Item>

          <Form.Item
            label="角色描述"
            labelAlign="left"
            name="description"
            rules={rules.description}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default Employees
